package org.richin.net.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookiePolicy;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.richin.collection.util.ArraysList;
import org.richin.lang.util.StringUtils;




public class HTMLCharSetCheck {
	static List<String> list=new ArraysList<String>();
	/**  
	 
     *<br>方法说明：得到网页编码格式  
 
     *<br>输入参数：strUrl 网页链接; timeout 超时设置  
 
     *<br>返回类型：网页编码  
 
     */  
  
    public static String getEncoding(String strUrl) {
    	
    	HttpClient httpClient=new HttpClient();
    	GetMethod getMethod =new GetMethod(strUrl);
    	String encodeString="";
    	try {
			httpClient.executeMethod(getMethod);
			
			InputStream input=getMethod.getResponseBodyAsStream();
			byte [] buffer=new byte[1024];
			
			while (input.read(buffer)!=-1) {
				encodeString=getEncdoer(new String(buffer));
				if(StringUtils.isNotEmpty(encodeString))
					break;
				
			}
			
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return encodeString; 
    	
    }
	public static String getEncdoer(String string)
	{
		Pattern p=Pattern.compile("charset\\s*=\\s*([^\"]+)");
		   Matcher m=p.matcher(string);
		   if(m.find())
		return m.group(1).toUpperCase();
		   return "";
	}
	public static void convert2Html(String sFilePath,String sSavePath,String sHtmlFile)
	{
		
		String baseHref="<base href='"+sFilePath+"'></base>";
	/*	String filePath = ru.getClass().getResource("").getPath().toString(); //取得项目根目录
		filePath = filePath.substring(1, filePath.indexOf("WEB-INF")); 
	*/
		String filePath="D:/web/";
		int HttpResult; 
		String SavePath = filePath + sSavePath; //保存路径 
		HttpClient httpClient=new HttpClient();
    	GetMethod getMethod =new GetMethod(sFilePath);
    	//getMethod.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");

    	String encodeString="";
    	
    	
    	try {
    		HttpResult=httpClient.executeMethod(getMethod);
    		System.out.println(HttpResult);
				encodeString=getEncdoer(getMethod.getResponseBodyAsString());	
				System.out.println("00"+encodeString);
				InputStreamReader isr = new InputStreamReader(getMethod.getResponseBodyAsStream(),encodeString); 

				BufferedReader in = new BufferedReader(isr); 
				String inputLine; 
				if(!SavePath.endsWith("/")) { 
				SavePath+="/"; 
				} 
				FileOutputStream fout = new FileOutputStream(SavePath+sHtmlFile); 
				//String regex="<a\\s+href\\s*=\\s*[\"\"|']?([^\"\"' ]*)[\"\"|']?[^<>]*>\\s*(<[^<>]+>)*([^<>]*)(<[^<>]+>)*\\s*</a>";  
				String regex="<.*src\\s*=\\s*[\"\"|']?([^\"\"' ]*)[\"\"|']?[^<>]*>.*</([^<>]*)>";
				while ((inputLine = in.readLine())!= null) 
				{ 		
					Pattern p=Pattern.compile(regex);
				   Matcher m=p.matcher(inputLine);
				   if(m.find())
					list.add(m.group(0));
				   //System.out.println(m.group(1));
				   //System.out.println(m..group(3));
				   
					
				     if(inputLine.toLowerCase().equals("<head>"))   
				         inputLine=inputLine+System.getProperty("line.separator")+baseHref;//加入basehref   
				         inputLine=inputLine+System.getProperty("line.separator");  //换行   
				        fout.write(inputLine.getBytes()); 
				}
				in.close(); 
				fout.close(); 
				//getMethod.releaseConnection();
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
finally{

}
		} 



	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		long star=System.currentTimeMillis();
convert2Html("http://www.memo110.com","/","55rti.htm");
		long end=System.currentTimeMillis();
		System.out.println(end-star);
		for(String string:list)
			System.out.println(string);
	}

}
